package com.smartcruise.task.newTask;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.codbking.calendar.CaledarAdapter;
import com.codbking.calendar.CalendarBean;
import com.codbking.calendar.CalendarDateView;
import com.codbking.calendar.CalendarLayout;
import com.codbking.calendar.CalendarUtil;
import com.codbking.calendar.CalendarView;
import com.smartcruise.R;
import com.smartcruise.base.BaseTitleFragment;
import com.smartcruise.base.TitleBuilder;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.util.Key;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.schedulerUtil.CronTransfer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.realm.RealmResults;

import static com.smartcruise.util.Utils.px;

/**
 * Created by FengChaoQun
 * on 2018/1/21 0021
 * 新任务界面
 */

public class NewTaskFragment extends BaseTitleFragment implements NewTaskContract.View {

    @BindView(R.id.calendarDateView)
    CalendarDateView calendarDateView;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.selectedDate)
    TextView selectedDate;
    @BindView(R.id.calendarLayout)
    CalendarLayout calendarLayout;
    private View headView;
    private View headText;
    private Calendar today = Calendar.getInstance();

    private NewTaskContract.Presenter mPresenter;

    @Override
    protected void init() {

        setEnableRightSlide(false);
        mPresenter = new NewTaskPresenterImp(this);

        calendarLayout.type = CalendarLayout.TYPE_OPEN;
        calendarDateView.setAdapter(new CaledarAdapter() {
            @Override
            public View getView(View convertView, ViewGroup viewGroup, CalendarBean bean) {
                TextView view;
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_calender, null);
                    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(px(48), px(48));
                    convertView.setLayoutParams(params);
                }

                view = convertView.findViewById(R.id.text);

                view.setText("" + bean.day);
//                if (bean.mothFlag != 0) {
//                    view.setTextColor(0xff9299a1);
//                } else {
//                    view.setTextColor(0xffffffff);
//                }

                Calendar calendar = Calendar.getInstance();
                calendar.set(bean.year, bean.moth - 1, bean.day);
                if (isHasTask(calendar)) {//有任务的日期标黄
                    view.setTextColor(getResources().getColor(R.color.yellowCollect));
                } else {
                    if (bean.mothFlag != 0) {
                        view.setTextColor(0xff9299a1);
                    } else {
                        view.setTextColor(0xffffffff);
                    }
                }

                return convertView;
            }
        });

        calendarDateView.setOnItemClickListener(new CalendarView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int postion, CalendarBean bean) {
                selectedDate.setText(bean.year + "/" + getDisPlayNumber(bean.moth) + "/" + getDisPlayNumber(bean.day));
                mPresenter.getData(bean);
            }
        });

        int[] data = CalendarUtil.getYMD(new Date());
        selectedDate.setText(data[0] + "/" + data[1] + "/" + data[2]);

        headView = getLayoutInflater().inflate(R.layout.util_header_textview, null);
        headText = headView.findViewById(R.id.headText);
        listView.addHeaderView(headView);
        mPresenter.start();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_container_new_task;
    }

    @Override
    protected TitleBuilder getTitleBuilder() {
        TitleBuilder titleBuilder = TitleBuilder.create(true, getString(R.string.taskSchedulers));
        titleBuilder.setShowRightImage(true);
        return titleBuilder;
    }

    @Override
    protected void clickOnRightImage() {
//        FragmentActivitySimpleImp.start(getContext(), TaskSearchFragment.class);
        Calendar calendar = Calendar.getInstance();
        calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
        Log.d("NewTaskFragment", "calendar:" + calendar);
        Log.d("NewTaskFragment", "today:" + today);
    }

    private String getDisPlayNumber(int num) {
        return num < 10 ? "0" + num : "" + num;
    }

    @Override
    public void setData(BaseAdapter adapter) {
        if (adapter.isEmpty()) {
            headText.setVisibility(View.VISIBLE);
        } else {
            headText.setVisibility(View.GONE);
        }
        listView.setAdapter(adapter);
    }

    private boolean isHasTask(Calendar calendar) {
        if (calendar.before(today)) {//过去的时间 不检查是否有任务
            return false;
        }

        if (TimeUtils.isSameDay(calendar.getTime(), today.getTime())) {//当天 检查是否有需要执行的任务
            //查询本地当天任务
            RealmResults<CruiseData> all = realm.where(CruiseData.class)
                    .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                    .equalTo(Key.isCopyData, true)
                    .equalTo(Key.statusInApp, CruiseContract.TASK_IS_WAIT_START)
                    .between(Key.shouldRunDate, TimeUtils.getDayBeginTime(calendar).getTime(), TimeUtils.getDayEndTime(calendar).getTime())
                    .findAll();
            return !all.isEmpty();
        }

        RealmResults<CruiseData> all = realm.where(CruiseData.class)
                .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                .equalTo(Key.isCopyData, false)
                .equalTo(Key.isFromNet, false)
                .findAll();

        List<CruiseData> cruiseDataList = new ArrayList<>();
        for (CruiseData cruiseData : all) {
            List<Date> dates = CronTransfer.computeFireTimesBetween(cruiseData.getCronExpression(),
                    TimeUtils.getDayBeginTime(calendar), TimeUtils.getDayEndTime(calendar));
            if (ListUtils.isHaveContent(dates)) {
                cruiseDataList.add(cruiseData);
            }
        }
        return !cruiseDataList.isEmpty();
    }
}
